# -*- coding: utf-8 -*-
import logging
import json
import oss2
import requests
from tablestore import *
from alitable import AliTableClient
from urllib.parse import quote

# To enable the initializer feature (https://help.aliyun.com/document_detail/2513452.html)
# please implement the initializer function as below：
# def initializer(context):
#   logger = logging.getLogger()
#   logger.info('initializing')

# *****************************************
# ****  Config Group 配置组   ****
#
# 填写RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
accessKeyId = 'LTAI5tRTUEa16q5Qv54TLaWr'
accessKeySecret = 'JWcUzk5acejkT1SzsCViFbKtYT7EmE'

# 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
auth = oss2.Auth(accessKeyId, accessKeySecret)

# 度惠 APPCode  https://market.console.aliyun.com/?spm=5176.12818093_-1363046575.top-nav.167.138e16d0fzSwjK#/bizlist?_k=cix47b

appcode = "24a31198c0a5444188dbdd1501d82b8f"

table_client = AliTableClient("https://pdfconvert.cn-shanghai.vpc.tablestore.aliyuncs.com","pdfconvert")

def handler(event, context):
    logger = logging.getLogger()

    # Load event content.
    oss_raw_data = json.loads(event)
    # print("执行")
    # print(event)
    # Get oss event related parameters passed by oss trigger.
    oss_info_map = oss_raw_data['events'][0]['oss']
    # Get oss bucket name.
    bucket_name = oss_info_map['bucket']['name']
    # Set oss service endpoint.
    endpoint = 'oss-' + oss_raw_data['events'][0]['region'] + '-internal.aliyuncs.com'
    # 文档转换这里不能使用阿里云内网访问
    # endpoint = 'oss-' + oss_raw_data['events'][0]['region'] + '.aliyuncs.com'
    # Initiate oss client.
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    object_name = oss_info_map['object']['key']
    object_ary = object_name.split('/')
    # Get task name
    task_name = object_ary[0]
    # Get file id.
    file_name = object_ary[1]
    file_id = file_name.split('.')[0]
    print(file_id)
    # Get file url
    # 一小时有效
    fileurl = bucket.sign_url('GET', object_name, 3600, slash_safe=True)
    print(fileurl)
    encoded_file_url = quote(fileurl,safe='')
    print(encoded_file_url)

    # Do Task
    request_token = None

    url = "https://pdf2doc.ali.duhuitech.com/v1/convert"
    headers = {"Authorization":"APPCODE "+appcode}
    params = {
        'url':encoded_file_url,
        'ocr':1
    }
    # 获取table中的配置
    row_info = table_client.get_one_row("tb_request",{'id':file_id})
    if row_info is None:
        # 没有配置，不做处理
        print("没有配置，不做处理")
        return
    
    columns = row_info["columns"]
    if "target_format" not in columns:
        # 没有目标文件格式
        print("没有目标文件格式")
        return
    params["type"] = columns["target_format"]

    if "password" in columns:
        params["password"] = columns["password"]
    if "ocr" in columns:
        params["ocr"] = columns["ocr"]
    if "language" in columns:
        params["language"] = columns["language"]
    
    pageindexes = None
    if "start_page" in columns:
        if "end_page" in columns:
            start_page = columns["start_page"]
            end_page = columns["end_page"]
            if (len(start_page) > 0) and (len(end_page) > 0):
                pageindexes = start_page + "-"+end_page

    if pageindexes is not None:
        params["pageindexes"] = pageindexes
            
    response = requests.get(url,headers=headers,params=params)

    if response.status_code == 200:
        response_json = response.json()
        request_token = response_json["result"]["token"]

        # 存储token到table
        table_client.update_one_row("tb_request",{'id':file_id},{'token':request_token})

    else:
        print(response.text)
        print(response.status_code)
        print(response.headers)
        print(response.reason)
        print(response.url)

    if request_token is not None:
        print(task_name + " : file_id = " + file_id + " request token = " + request_id)
    
    return

if __name__ == '__main__':
    bucket = oss2.Bucket(auth, "oss-cn-shanghai-internal.aliyuncs.com", 'sh-pdftoconvert')
    fileurl = bucket.sign_url('GET', 'object_name', 3600, slash_safe=True)
    print(fileurl)
    encoded_file_url = quote(fileurl,safe='')
    print(encoded_file_url)

    url = "https://pdf2doc.ali.duhuitech.com/v1/convert"
    params = {}
    headers = {"Authorization":"APPCODE "+appcode}

    response = requests.get(url,headers=headers,params=params)
    if response.status_code == 200:
        response_json = response.json()
        token = response_json["result"]["token"]
    else:
        print(response.text)
        print(response.status_code)
        print(response.headers)
        print(response.reason)
        print(response.url)